﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;
using WebMatrix.WebData;
using PlanificadorDeEventos.Models;
using PlanificadorDeEventos.Repositorios;
using PlanificadorDeEventos.Comun;
using System.Collections.Generic;

namespace PlanificadorDeEventos.Seguridad
{
    public class CustomMembershipProvider : ExtendedMembershipProvider
    {
        RepositorioGuests repoGuest = new RepositorioGuests(ModelContext.Instance);
        RepositorioEventoUsuarioRegistrados repoUsuarioRegistrado = new RepositorioEventoUsuarioRegistrados(ModelContext.Instance);

        public override bool ConfirmAccount(string accountConfirmationToken)
        {
            throw new NotImplementedException();
        }

        public override bool ConfirmAccount(string userName, string accountConfirmationToken)
        {
            throw new NotImplementedException();
        }

        public override string CreateAccount(string userName, string password, bool requireConfirmationToken)
        {
            throw new NotImplementedException();
        }

        public override string CreateUserAndAccount(string userName, string password, bool requireConfirmation, System.Collections.Generic.IDictionary<string, object> values)
        {
           // if (repoGuest.ObtenerPorNombre(userName) != null)
           //     return "fail";


            User user = new User();
            Object email="";
            if (values.TryGetValue("email", out email))
                user.Email = (String)email;

            Guest guest = repoGuest.ObtenerPorNombre(userName);

            if (guest != null && guest.Email != user.Email) //ya existe el nombre de usuario
            {
                return "fail";
            }

            if (guest!=null) 
            {
                actualizarDatosDeUsuario(guest, password);
                return "success";
            }

            user.Nombre = userName;
            user.Password = password;
            if (values.TryGetValue("email", out email))
                user.Email = (String)email;
            repoGuest.Insert(user);
            return "success";
        }

        private void actualizarDatosDeUsuario(Guest guest,string password)
        {
            User user = new User();
            user.Nombre = guest.Nombre;
            user.Email = guest.Email;
            user.Password = password;
            repoGuest.Insert(user);

            IEnumerable<EventoUsuarioRegistrado> eur = repoUsuarioRegistrado.ObtenerPorIdUser(guest.ID);
            foreach (var eventReg in eur) 
            {
                EventoUsuarioRegistrado eventoRegistrado = new EventoUsuarioRegistrado();
                eventoRegistrado.confirmado = eventReg.confirmado;
                eventoRegistrado.EventoID = eventReg.EventoID;
                eventoRegistrado.GuestID = user.ID;
                repoUsuarioRegistrado.Insert(eventoRegistrado);
                repoUsuarioRegistrado.Delete(eventReg);
            }
            repoGuest.Delete(guest);

        }

        public override bool DeleteAccount(string userName)
        {
            throw new NotImplementedException();
        }

        public override string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow)
        {
            throw new NotImplementedException();
        }

        public override System.Collections.Generic.ICollection<OAuthAccountData> GetAccountsForUser(string userName)
        {

            return new OAuthAccountData[0];
        }

        public override DateTime GetCreateDate(string userName)
        {
            throw new NotImplementedException();
        }

        public override DateTime GetLastPasswordFailureDate(string userName)
        {
            throw new NotImplementedException();
        }

        public override DateTime GetPasswordChangedDate(string userName)
        {
            throw new NotImplementedException();
        }

        public override int GetPasswordFailuresSinceLastSuccess(string userName)
        {
            throw new NotImplementedException();
        }

        public override int GetUserIdFromPasswordResetToken(string token)
        {
            return repoGuest.ObtenerPorNombre(token).ID;
        }

        public override bool IsConfirmed(string userName)
        {
            throw new NotImplementedException();
        }

        public override bool ResetPasswordWithToken(string token, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            User user = (User)repoGuest.ObtenerPorNombre(username);
            if (user.Password.Equals(oldPassword))
            {
                user.Password = newPassword;
                repoGuest.Update(user);
                return true;
            }
            return false;
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            throw new NotImplementedException();

        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {


            var user = repoGuest.ObtenerPorNombre(username);
            if (user == null)
            {
                return null;
            }
            return new MembershipUser(Membership.Provider.Name, username, user.ID, null, null, null, true, false, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue);
            
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { throw new NotImplementedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new NotImplementedException(); }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            User user;
            try
            {    
                user = (User)repoGuest.ObtenerPorNombre(username);
            }
            catch(Exception)
            {
                return false;
            }
            return (user!=null && user.Password.Equals(password));
        }


        public override int GetUserIdFromOAuth(string provider, string providerUserId)
        {
            throw new NotImplementedException();
        }
       
    }
}